package com.example.common.util;

import com.example.common.entity.BaseUserInfo;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求处理工具类
 */
public class RequestUtil {

    private static final String  PARAM_ARR_SPLIT = "&";

    private static final String  PARAM_SPLIT = "=";

    public static Map<String,String>  getParamMap(String paramsStr){

        Map<String, String> paramsMap = new HashMap<>();

        if (paramsStr.contains(PARAM_ARR_SPLIT)) {
            //  ["a=1","b=2"]
            String[] splitArr = paramsStr.split(PARAM_ARR_SPLIT);

            for (String arr : splitArr) {
                //["a","1"]
                String[] paramArr = arr.split(PARAM_SPLIT);
                if (paramArr.length > 0) {
                    paramsMap.put(paramArr[0], paramArr[1]);
                }
            }
        }else {
            String[] paramArr = paramsStr.split(PARAM_SPLIT);
            if (paramArr.length > 0) {
                paramsMap.put(paramArr[0], paramArr[1]);
            }
        }
        return paramsMap;

    }

    /**
     * 获取用户基本信息
     * @param uri
     * @return
     */
    public static BaseUserInfo  getBaseUserInfor(URI uri){

        String path = uri.toString();

        // a=1&b=2
        String paramsStr = path.substring(path.lastIndexOf("?") + 1);

        Map<String, String> paramsMap = RequestUtil.getParamMap(paramsStr);

        BaseUserInfo baseUserInfo = GsonUtils.copyProperties(paramsMap, BaseUserInfo.class);

        return baseUserInfo;

    }

}
